import { defineStore } from "pinia"
import { ref, computed } from 'vue'

export const useUserStore = defineStore("user", () => {
	
	const key = "USERINFO"
	var  initData = uni.getStorageSync(key)
	
	if(typeof initData == 'string') {
		initData = {
			openid: '',
			name: '',
			avat: ''
		}
	}
	
	const userInfo = ref(initData)
	
	const isLogined = computed(() => !! userInfo.value.openid)
	const role = computed(() => userInfo.value.role)
	const openid = computed(() => userInfo.value.openid)
	const cache = () => {
		uni.setStorageSync(key, userInfo.value)
	}
	
	const setUserInfo = (info) => {
		userInfo.value = info
		cache()
	}
	
	const setName = (name:string) => {
		userInfo.value.name = name
		cache()
	}
	
	const logOut = () => {
		userInfo.value = {
			openid: '',
			name: '',
			avat: ''
		}
		uni.removeStorageSync(key)
	}
	return {
		userInfo,
		setName,
		setUserInfo,
		isLogined,
		role,
		openid,
		logOut,
	}
})